package DFS;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Solution39 {


    public static void main(String[] args) {
        int[] nums = new int[]{100, 200, 4, 12};
        System.out.println(combinationSum(nums, 400));
    }

    public static List<List<Integer>> combinationSum(int[] nums, int target) {
        List<Integer> chain = new ArrayList<>();
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        dfs(nums, target, 0, 0, chain, res);
        return res;
    }

    public static void dfs(int[] nums, int target, int sum, int index, List<Integer> chain, List<List<Integer>> res) {
        if (sum > target) {
            return;
        }

        if (sum == target) {
            List<Integer> list = new ArrayList<>(chain);
            res.add(list);
            return;
        }

        for (int i = index; i < nums.length; i++) {
            if (sum + nums[i] > target) {
                break;
            }
            if (chain.size() > 150) {
                break;
            }
            chain.add(nums[i]);
            sum += nums[i];
            System.out.println("递归之前 => " + chain + "，剩余 = " + sum);
            dfs(nums, target, sum, i, chain, res);
            System.out.println("递归之后 => " + chain + "，剩余 = " + sum);
            chain.remove(chain.size() - 1);
            sum -= nums[i];
        }

    }


}
